package com.tduck.cloud.form.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.tduck.cloud.form.entity.UserFormEntity;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.util.List;
import java.util.Map;

/**
 * 表单表(Form)表数据库访问层
 *
 * @author smalljop
 * @since 2020-11-18 18:16:17
 */
public interface UserFormMapper extends BaseMapper<UserFormEntity> {

    @Select("<script>" +
            " SELECT " +
            "COUNT(DISTINCT a.id) AS totalOfQuestionnaire,COUNT(DISTINCT b.id) AS cumulativeNumber," +
            "COUNT(*) AS totalCollection," +
            "COUNT(CASE WHEN DATE(b.create_time) = CURDATE() THEN 1 END) AS todayCollection" +
            " FROM fm_user_form a left join fm_user_form_data b on a.key = b.form_key and b.delete_flag = 0 " +
            "<when test='beginDate != null'>" +
            "   and b.create_time &gt;= #{beginDate}" +
            "</when>" +
            "<when test='endDate != null'>" +
            "   and b.create_time &lt; #{endDate}" +
            "</when>" +
            " where a.type = 1 AND a.status = 2 AND a.is_deleted = 0 " +
            "<when test='key != null'>" +
            "   and a.key = #{key}" +
            "</when>" +
            "<when test='hospitalCode != null'>" +
            "   and a.hospital_code = #{hospitalCode}" +
            "</when>" +
            "</script>")
    Map<String,Integer> getTotalCount(@Param("key") String key,@Param("hospitalCode") String hospitalCode,@Param("beginDate") String beginDate,@Param("endDate") String endDate);

    @Select("<script>" +
            " SELECT " +
            " DATE_FORMAT(b.create_time, '%m-%d') AS date,COUNT(*) AS num" +
            " FROM fm_user_form a left join fm_user_form_data b on a.key = b.form_key and b.delete_flag = 0 " +
            "<when test='beginDate != null'>" +
            "   and b.create_time &gt;= #{beginDate}" +
            "</when>" +
            "<when test='endDate != null'>" +
            "   and b.create_time &lt; #{endDate}" +
            "</when>" +
            " where b.create_time is not null and a.type = 1 AND a.status = 2 AND a.is_deleted = 0 " +
            "<when test='hospitalCode != null'>" +
            "   and a.hospital_code = #{hospitalCode}" +
            "</when>" +
            "GROUP BY YEAR(b.create_time),DATE_FORMAT(b.create_time, '%m-%d')" +
            "ORDER BY YEAR(b.create_time),DATE_FORMAT(b.create_time, '%m-%d')" +
            "</script>")
    List<Map<String,Integer>> getDateCount(@Param("hospitalCode") String hospitalCode,@Param("beginDate") String beginDate,@Param("endDate") String endDate);

}